<?php
namespace app\admin\controller;

use app\admin\controller\Base;
//use think\facade\Config;

class Role extends Base
{

    public function index()
    {
        // 当前页码
        $page = request()->param('page', '1');
        $limit = request()->param('limit', 10);
        $title = request()->param('title', '');

        // 总数
        $total = model('AdminRole')->count();
        // 搜索条件
        $where = [];
        if ($title) {
            $where[] = ['title', 'like', '%'. $title. '%'];
        }
        $list = model('AdminRole')->where($where)->page($page, $limit)->select();

        $data = [
            'total' => $total,
            'list' => $list,
        ];
        return $this->ok($data);
    }

    public function detail()
    {
        // 当前用户
        $id = request()->param('id');
        $data = model('AdminRole')->where('id', $id)->find();
        return $this->ok($data);
    }

    public function save()
    {
        // 过滤字段
        $param = request()->only(['id', 'title', 'auth']);
        model('AdminRole')->saveData($param);
        return $this->ok('更新成功');
    }

    public function del()
    {
        // 过滤字段
        $id = request()->param('id');
        $data = model('AdminRole')->where('id', $id)->find();
        if (empty($data)) {
            $this->fail('角色不存在');
        }
        if ($data['is_super']) {
            $this->fail('角色不能删除');
        }
        $result = model('AdminRole')->delData($id);
        if ($result) {
            return $this->ok('删除成功');
        } else {
            return $this->fail('删除失败');
        }
    }

    public function auth()
    {
        $id = request()->param('id');
        $authKeyList = model('AdminRole')->getAuth($id);
        $authList = config('auth.auth');
        $data = [
            'authKeyList' => $authKeyList,
            'authList' => $authList,
        ];
        return $this->ok($data);
    }

    public function setAuth()
    {
        $param = [
            'id' => request()->param('id'),
            'auth' => request()->param('authRules'),
        ];
        model('AdminRole')->saveAuth($param);
        return $this->ok('更新成功');
    }

}